package com.shwread.android.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.ChatPersonalInfoActivity;
import com.shwread.android.qysw.activity.NewInteractionAtlasSeeActivity;
import com.shwread.android.qysw.activity.NewInteractionDetailsActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.customview.NoScrollGridView;
import com.shwread.android.ui.dialog.CommonDialog;
import com.shwread.android.ui.dialog.SimpleListener;
import com.shwread.android.ui.page.chat.MomentsPage;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.GroupBean;
import logic.bean.NewInteractionColumn;
import logic.bean.NewInteractionInfo;
import logic.bean.PageBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.GroupDao;
import logic.util.DateUtil;
import logic.util.Util;
import logic.util.Utils;


/**
 * 互动中心的内容视图
 *
 * @author zouqp
 *         2015-03-03
 */

public class NewInteractionContentView
        extends
        LinearLayout
        implements
        OnScrollListener,
        OnItemClickListener {
    public static final int PAGESIZE = 5;
    public static final int IMAGE_COUNT = 5;
    private static final char REGION_SPLITOR = 8;
    private int mTotalItemCount = 0;
    private MyListView mContentListView;
    private Context mContext;                                                      //
    private ContentAdapter mContentAdapter;
    private boolean hasMore = true;
    List<NewInteractionInfo> mContentItemList = new ArrayList<NewInteractionInfo>();      //内容项列表
    private int currentPage = 1;
    private ImageView switchImg;
    private View switchView;
    private AnimationDrawable switchDrawable;
    private BaseBusinessActivity baseActivity;
    private InteractionContentViewListener contentViewListener;
    private long currentPublishTime = 0;
    private RelativeLayout rl_blank_content;
    /**
     * myRefreshFlag 0 首次进入 -- 1为 下拉刷新 -- 2加载更多
     **/
    private int myRefreshFlag = 0;                                        //0 首次进入  1为 下拉刷新， 2加载更多
    private int fromType;                                                      //页面类型   0 为普通用户页面    1为客户经理页面  2 为客户
    private PageBean pageDto;                                                       //保存分页信息
    private HashMap<Integer, ArrayList<String>> mapLists = new HashMap<Integer, ArrayList<String>>();
    private List<List<Integer>> list4;
    public static HashMap<Integer, List<Integer>> mapList5 = new HashMap<Integer, List<Integer>>();
    private AddressBookInfoDao addressBookInfoDao;
    private GroupDao groupDao;

    /**
     * @param context
     */
    public NewInteractionContentView(Context context) {
        super(context);
        mContext = context;
        initWithContext(context);
    }

    public NewInteractionContentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    @SuppressLint("NewApi")
    public NewInteractionContentView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    public int getFromType() {
        return fromType;
    }

    public void setFromType(int fromType) {
        this.fromType = fromType;
    }

    private void initWithContext(Context context) {
        addressBookInfoDao = AddressBookInfoDao.getInstance(mContext);
        groupDao = GroupDao.getInstance(mContext);
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        LinearLayout containerView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.interaction_view_layout, null);
        mContentListView = (MyListView) containerView.findViewById(R.id.lv_interaction_content);
        switchImg = (ImageView) containerView.findViewById(R.id.column_switch_img);
        switchView = containerView.findViewById(R.id.column_switch_layout);
        rl_blank_content = (RelativeLayout) containerView.findViewById(R.id.rl_blank_content);

        addView(containerView, lp);
        mContentListView.setOnScrollListener(this);
        mContentListView.setOnItemClickListener(this);
        mContentAdapter = new ContentAdapter();
        mContentListView.setAdapter(mContentAdapter);
    }

    public void setBaseActivity(BaseBusinessActivity baseActivity) {
        this.baseActivity = baseActivity;
    }

    /**
     * @param getDataType 获取数据的方式 0 首次进入 有加载动画 1为刷新 2为加载更多
     */
    public void getInteractionData(int getDataType) {
        mContentListView.setFocusable(false);
        if (fromType == 2 || fromType == 0)//TODO 获取普通用户page数据
        {
            getNormalData(getDataType);
        } else if (fromType == 1)//TODO 获取经理page数据
        {
            getNormalData(getDataType);
        }

    }

    public void setInteractionContentViewListener(InteractionContentViewListener contentViewListener) {
        this.contentViewListener = contentViewListener;
    }

    public int getDataSize() {
        return (mContentItemList == null || mContentItemList.isEmpty()) ? 0 : mContentItemList.size();
    }

    public int getTotalItemCount() {
        return mTotalItemCount;
    }

    public void getNextPage() {
        if (fromType == 2 || fromType == 0) {
            getNormalData(2);
        } else if (fromType == 1) {
            getNormalData(2);
        }
    }

    public boolean isGotMaxSize() {
        if (mTotalItemCount < PAGESIZE) {
            return false;
        } else {
            return true;
        }

    }

    public boolean getHasMore() {
        if (mTotalItemCount < PAGESIZE) {
            hasMore = false;
        } else {
            hasMore = true;
        }

        return hasMore;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // send to user's listener
        //		mTotalItemCount = totalItemCount;
        //		if (canUpdate && hasMore && totalItemCount != 0 && totalItemCount - firstVisibleItem - visibleItemCount <= 5 ) {
        //			getFakeContentItemData( );
        //			mContentAdapter.notifyDataSetChanged();
        //		}
    }

    private void refreshUIData() {
        mapLists.clear();
        mapList5.clear();
        if (contentViewListener != null) {
            contentViewListener.OnLoadDataCompleted(2);
        }
        mContentAdapter.notifyDataSetChanged();
    }

    /******************************
     * list 的 item click 方法
     *****************************************/

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NewInteractionInfo contentItem = mContentItemList.get(position);
        Intent intent = new Intent();
        intent.setClass(mContext, NewInteractionDetailsActivity.class);
        intent.putExtra("NewInteractionInfo", contentItem);
        intent.putExtra("position", position);
        intent.putExtra("delete", mContentItemList.get(position).getAuthorId() + "");
        if (Utils.isNotEmpty(mContentItemList.get(position).getImageList())) {
            String[] strArray = null;
            strArray = mContentItemList.get(position).getImageList().split(",");
            final List<String> list = new ArrayList<String>();
            for (String url : strArray) {
                list.add(url);
            }
            if (list.size() == 1) {
                intent.putExtra("width", mapList5.get(position).get(0));
                intent.putExtra("height", mapList5.get(position).get(1));
            }
        }
        baseActivity.startActivityForResult(intent, BaseBusinessActivity.COMMENTS_REQUEST_CODE);
    }

    public void updateComment(int position, int count) {
        NewInteractionInfo info = mContentItemList.get(position);
        info.setCommentNum(count + "");
        mContentAdapter.notifyDataSetChanged();
    }

    /****************************** 一些私有的方法 *****************************************/

    /**
     * 栏目切换加载动画
     *
     * @param flag 0:加载中，1：加载完成，2: 内容为空 -1：加载失败
     */
    public void updateSwitchView(int flag) {
        switch (flag) {
            case -1:
                switchView.setVisibility(View.VISIBLE);
                rl_blank_content.setVisibility(View.GONE);
                mContentListView.setVisibility(View.GONE);
                if (switchDrawable != null && switchDrawable.isRunning()) {
                    switchDrawable.stop();
                }
                //TODO
                switchImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                switchView.setVisibility(View.VISIBLE);
                mContentListView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.GONE);
                switchImg.setBackgroundResource(R.drawable.home_progress);
                switchDrawable = (AnimationDrawable) switchImg.getBackground();
                switchDrawable.start();
                break;
            case 1:
                switchView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.GONE);
                mContentListView.setVisibility(View.VISIBLE);
                break;
            case 2:
                switchView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.VISIBLE);
                mContentListView.setVisibility(View.GONE);
                break;
        }
    }

    public static interface InteractionContentViewListener {
        /**
         * @param flag 0为首次进入 1为刷新装载， 2 为装载更多
         */
        public void OnLoadDataCompleted(int flag);
    }

    /**
     * 获取普通用户信息
     *
     * @param getDataType 数据获取操作类型 1为刷新 2为加载更多
     */
    private void getNormalData(int getDataType) {
        this.myRefreshFlag = getDataType;
        if (getDataType != 2) {
            currentPage = 1;
        } else {
            currentPage++;
        }
        NewActionHelp.qryTopicList(mContext, currentPage, PAGESIZE, 0, new GetNormalDataHandler());
    }

    /**
     * 获取客户经理信息
     *
     * @param getDataType 数据获取操作类型 1为刷新 2为加载更多
     */
    private void getMangerData(int getDataType) {
        this.myRefreshFlag = getDataType;
        if (getDataType != 2) {
            currentPublishTime = 0L;
        } else {
            currentPublishTime = mContentItemList.get(mContentItemList.size() - 1).getPublishTime();
        }
        NewActionHelp.qryTopicActivityList(mContext, currentPublishTime, PAGESIZE, new GetMangerDataHandler());
    }

    /***************************** 获取数据的监听事件 ******************************************/

    /**
     * @author zhangnannan
     * @project newInteraction
     * @description 普通用户获取数据的监听事件
     * @Time 2015年5月12日 下午4:23:56
     */
    class GetNormalDataHandler
            extends
            ObjectHttpResponseHandler<NewInteractionColumn> {

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#onFailure(int,
         * org.apache.http.Header[], java.lang.String, java.lang.Throwable)
         */
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Logger.e(throwable);
            if (myRefreshFlag == 0) updateSwitchView(-1);
            if (contentViewListener != null) {
                contentViewListener.OnLoadDataCompleted(2);
            }
        }

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#onSuccess(int,
         * org.apache.http.Header[], java.lang.Object, java.lang.String)
         */
        @Override
        public void onSuccess(int statusCode, Header[] headers, NewInteractionColumn object, String responseString) {
            Logger.i(responseString);
            if (object != null && object.getContentList() != null && object.getContentList().size() > 0) {
                if (myRefreshFlag == 0) {
                    updateSwitchView(1);
                }
                if (myRefreshFlag != 2)//下拉
                {
                    if (mContentItemList.size() > 0) mContentItemList.clear();
                    mContentItemList.addAll(object.getContentList());
                } else
                //上拉加载
                {
                    mContentItemList.addAll(object.getContentList());
                }
                pageDto = object.getPageDto();
                mTotalItemCount = object.getContentList().size();
                updateSwitchView(1);
                baseActivity.getUIHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        refreshUIData();
                    }
                });

            } else {
                mTotalItemCount = 0;
                hasMore = false;
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (contentViewListener != null) {
                            contentViewListener.OnLoadDataCompleted(2);//装载更多
                        }
                        if (myRefreshFlag == 0) {//只有当前是重新刷新时， 才更新ui为无内容
                            updateSwitchView(2);//内容为空
                        }
                    }
                });

            }
            if ((myRefreshFlag == 0 || myRefreshFlag == 1) && object != null && object.getContentList() != null && object.getContentList().size() == 0) {
                updateSwitchView(2);
            }

        }

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#getType()
         */
        @Override
        public Type getType() {
            // TODO Auto-generated method stub
            return new TypeToken<NewInteractionColumn>() {
            }.getType();
        }

    }

    /**
     * @author zhangnannan
     * @project newInteraction
     * @description 客户经理获取数据的监听事件
     * @Time 2015年5月12日 下午4:23:56
     */

    class GetMangerDataHandler
            extends
            ObjectHttpResponseHandler<List<NewInteractionInfo>> {

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#onFailure(int,
         * org.apache.http.Header[], java.lang.String, java.lang.Throwable)
         */
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Logger.e(throwable);
            if (myRefreshFlag == 0) {
                updateSwitchView(-1);
            }

        }

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.kk#onSuccess(int,
         * org.apache.http.Header[], java.lang.Object, java.lang.String)
         */
        @Override
        public void onSuccess(int statusCode, Header[] headers, List<NewInteractionInfo> object, String responseString) {
            if (object != null) {
                if (myRefreshFlag == 0) {
                    updateSwitchView(1);
                }
                if (myRefreshFlag != 2) {
                    if (mContentItemList.size() > 0) mContentItemList.clear();
                    mContentItemList.addAll(object);
                } else {
                    mContentItemList.addAll(object);
                }
                mTotalItemCount = object.size();
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        refreshUIData();
                    }
                });
            } else {
                hasMore = false;
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (myRefreshFlag == 0) updateSwitchView(2);
                        refreshUIData();
                    }
                });
            }

        }

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#getType()
         */
        @Override
        public Type getType() {
            // TODO Auto-generated method stub
            return new TypeToken<List<NewInteractionInfo>>() {
            }.getType();
        }

    }

    /******************************
     * list 的适配器
     *****************************************/
    private class ContentAdapter
            extends
            BaseAdapter {
        private final int Type_0 = 0;
        private final int Type_1 = 1;
        private List<ImageView> imaList = new ArrayList<ImageView>();
        private ImageView ima;
        private ArrayList<String> list;
        private List<String> list2;
        private List<Integer> list3;
        private List<Integer> list4_1;

        @Override
        public int getCount() {
            if (mContentItemList == null) {
                return 0;
            } else {
                //				return mContentItemList.size();
                return mContentItemList.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return mContentItemList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            String imgstr = mContentItemList.get(position).getImageList();
            if (Utils.isNotEmpty(imgstr)) {
                return Type_1;
            } else {
                return Type_0;
            }
        }

        @Override
        public int getViewTypeCount() {
            // TODO Auto-generated method stub
            return 2;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final NewInteractionInfo contentItem = mContentItemList.get(position);
            int type = getItemViewType(position);
            SingleinfoViewHolder singleInfo;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.new_interaction_singleinfo_item, null);//
                //				convertView.setTag(0);
                singleInfo = new SingleinfoViewHolder();
                singleInfo.tv_info_title = (TextView) convertView.findViewById(R.id.new_tv_info_title);//楼主
                singleInfo.im_headportrait = (ImageView) convertView.findViewById(R.id.new_im_headportrait);//楼主头像
                singleInfo.tv_info_from = (TextView) convertView.findViewById(R.id.new_tv_info_from);//内容
                singleInfo.tv_publishtime = (TextView) convertView.findViewById(R.id.new_tv_publishtime);//时间
                //评论
                singleInfo.tv_comments_count = (TextView) convertView.findViewById(R.id.new_tv_comments_count);
                singleInfo.tv_comments_count.setVisibility(View.VISIBLE);
                singleInfo.im_comments = (ImageView) convertView.findViewById(R.id.new_im_comments);
                singleInfo.im_comments.setVisibility(View.VISIBLE);
                singleInfo.im_bigimage_ll = (RelativeLayout) convertView.findViewById(R.id.new_im_bigimage_ll);
                singleInfo.im_bigimage = (ImageView) convertView.findViewById(R.id.new_im_bigimage);//图片
                singleInfo.im_atlas = (ImageView) convertView.findViewById(R.id.new_im_atlas);
                singleInfo.im_atlas.setTag(position);
                singleInfo.tv_delete = (TextView) convertView.findViewById(R.id.tv_delete);
                singleInfo.tv_delete.setTag(position);
                singleInfo.gridView = (NoScrollGridView) convertView.findViewById(R.id.gridview);
                singleInfo.gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
                if (type == Type_0) {
                    singleInfo.im_bigimage_ll.setVisibility(View.GONE);
                }

                convertView.setTag(singleInfo);
            } else {
                singleInfo = (SingleinfoViewHolder) convertView.getTag();
            }
            if (Const.UserStaffId.equals(mContentItemList.get(position).getAuthorId() + "")) {
                singleInfo.tv_delete.setVisibility(View.VISIBLE);
            } else {
                singleInfo.tv_delete.setVisibility(View.GONE);
            }
            // 填充数据
            //返回的数据是否为手机号，显示账号中间****
            if (Utils.isMobile(contentItem.getAuthorName())) {
                singleInfo.tv_info_title.setText(Util.formatPhone(contentItem.getAuthorName()));
            } else {
                singleInfo.tv_info_title.setText(contentItem.getAuthorName());
            }
            //需判断  是否为经理  是否有设置头像
            singleInfo.im_managerlabel = (ImageView) convertView.findViewById(R.id.new_im_manager_label);//经理的标注
            if ((contentItem.getAutorRole()).equals("3"))//系统
            {
                singleInfo.im_managerlabel.setVisibility(View.GONE);
//                singleInfo.im_headportrait.setImageResource(R.drawable.new_i_recommend_theme);
                GlideUtil.roundnesslocalload(mContext,R.drawable.new_i_recommend_theme,singleInfo.im_headportrait);
                singleInfo.tv_info_title.setText("推荐主题");
            } else if ((contentItem.getAutorRole()).equals("1")) {//经理
                singleInfo.im_managerlabel.setVisibility(View.VISIBLE);
                GlideUtil.roundnessload(mContext,contentItem.getAuthorHeaderImage(),R.drawable.new_i_head_protrait_empty_icon,singleInfo.im_headportrait);
            } else if ((contentItem.getAutorRole()).equals("2") || (contentItem.getAutorRole()).equals("0")) {// 2   为客户    0为普通用户
                singleInfo.im_managerlabel.setVisibility(View.GONE);
                GlideUtil.roundnessload(mContext,contentItem.getAuthorHeaderImage(),R.drawable.new_i_head_protrait_empty_icon,singleInfo.im_headportrait);
            }
            String contenttext = contentItem.getContent();
            singleInfo.tv_info_from.setText(contenttext);

            final String imagelist = contentItem.getImageList();//图片字符串
            final String imageSizeList = contentItem.getImageSizeList();
            if (Utils.isNotEmpty(imagelist)) {
                String[] strArray = null;
                strArray = imagelist.split(",");
                String[] strArray2 = null;
                strArray2 = imageSizeList.split("\\,");
                //				if (strArray.length == 1)
                //				{
                //					singleInfo.im_atlas.setVisibility(View.GONE);//隐藏图集标注
                //				}
                //				else
                //				{
                //					//					singleInfo.im_atlas.setVisibility(View.VISIBLE);
                //					//					singleInfo.im_atlas.setVisibility(View.GONE);//隐藏图集标注
                //				}
                list = new ArrayList<String>();
                list4 = new ArrayList<List<Integer>>();
                for (String url : strArray) {
                    list.add(url);
                }
                for (String str : strArray2) {
                    list3 = new ArrayList<Integer>();
                    String[] strArray3 = null;
                    strArray3 = str.split("\\*");
                    for (String str3 : strArray3) {

                        int a = Integer.parseInt(str3);
                        list3.add(a);
                    }
                    list4.add(list3);
                }
                mapLists.put(position, list);
                GlideUtil.load(mContext,strArray[0], singleInfo.im_bigimage);
                if (MomentsPage.width == 480) singleInfo.gridView.setVerticalSpacing(3);
                if (list.size() == 4) {
                    singleInfo.gridView.setNumColumns(2);
                    singleInfo.gridView.setPadding(0, 0, (MomentsPage.width * 3 / 4 - 10) / 3 + 5, 0);
                } else {
                    singleInfo.gridView.setNumColumns(3);
                    singleInfo.gridView.setPadding(0, 0, 0, 0);
                }

                singleInfo.gridView.setAdapter(new GridViewAdapter(list, list4));
                //				singleInfo.im_bigimage.setOnClickListener(new OnClickListener()
                //				{
                //
                //					@Override
                //					public void onClick(View arg0) {
                //						Intent AtlasSeeIntent = new Intent();
                //						AtlasSeeIntent.setClass(mContext, NewInteractionAtlasSeeActivity.class);
                //						AtlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, List);
                //						AtlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_WEBURL);
                //						mContext.startActivity(AtlasSeeIntent);
                //					}
                //				});
                if (list.size() == 1) {
                    //					convertView.setTag(1);
                    singleInfo.gridView.setVisibility(View.GONE);
                    int widthIma, heightIma;//计算图片比列
                    widthIma = list4.get(0).get(0) / 2;
                    heightIma = list4.get(0).get(1) / 2;
                    if (widthIma > MomentsPage.width * 3 / 4 && heightIma < 1200) {
                        heightIma = heightIma * (MomentsPage.width * 3 / 4) / widthIma;
                        widthIma = MomentsPage.width * 3 / 4;

                    }
                    if (heightIma >= 1200 && widthIma <= MomentsPage.width * 3 / 4) {
                        widthIma = widthIma * 1200 / heightIma;
                        heightIma = 1200;
                    }

                    if (heightIma > 1200 && widthIma > MomentsPage.width * 3 / 4) {

                        if (widthIma * 1200 / heightIma > widthIma * 3 / 4) {
                            heightIma = heightIma * (MomentsPage.width * 3 / 4) / widthIma;
                            widthIma = MomentsPage.width * 3 / 4;
                        } else {
                            widthIma = widthIma * 1200 / heightIma;
                            heightIma = 1200;
                        }

                    }
                    if (list4 != null && list4.size() > 0)
                        singleInfo.im_atlas.setLayoutParams(new LayoutParams(widthIma, heightIma));
                    else {
                        singleInfo.im_atlas.setLayoutParams(new LayoutParams(300, 500));

                    }
                    singleInfo.im_atlas.setVisibility(View.VISIBLE);
                    GlideUtil.load(mContext,list.get(0), singleInfo.im_atlas);
                    //Glide.with(mContext).load(list.get(0)).placeholder(R.drawable.moments_default_bg).into(singleInfo.im_atlas);
                    list4_1 = new ArrayList<Integer>();
                    list4_1.add(widthIma);
                    list4_1.add(heightIma);
                    mapList5.put(position, list4_1);

                } else {
                    singleInfo.gridView.setVisibility(View.VISIBLE);
                    singleInfo.im_atlas.setVisibility(View.GONE);
                }
            }
            singleInfo.tv_publishtime.setText(DateUtil.getRegionTime(contentItem.getPublishTime()));
            singleInfo.tv_comments_count.setText(contentItem.getCommentNum() + "");
            if (Integer.parseInt(contentItem.getCommentNum()) > 99)
                singleInfo.tv_comments_count.setText("99+");
            if (contentItem.getCommentNum().equals("0"))
                singleInfo.tv_comments_count.setTextColor(0xffffffff);
            else singleInfo.tv_comments_count.setTextColor(0xff838383);
            singleInfo.im_comments.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    NewInteractionInfo contentItem = mContentItemList.get(position);
                    Intent intent = new Intent();
                    intent.setClass(mContext, NewInteractionDetailsActivity.class);
                    intent.putExtra("NewInteractionInfo", contentItem);
                    intent.putExtra("position", position);
                    intent.putExtra("delete", mContentItemList.get(position).getAuthorId() + "");
                    if (Utils.isNotEmpty(mContentItemList.get(position).getImageList())) {
                        String[] strArray = null;
                        strArray = mContentItemList.get(position).getImageList().split(",");
                        final List<String> list = new ArrayList<String>();
                        for (String url : strArray) {
                            list.add(url);
                        }
                        if (list.size() == 1) {
                            intent.putExtra("width", mapList5.get(position).get(0));
                            intent.putExtra("height", mapList5.get(position).get(1));
                        }
                    }
                    baseActivity.startActivityForResult(intent, BaseBusinessActivity.COMMENTS_REQUEST_CODE);

                }
            });
            singleInfo.tv_delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonDialog dialog = new CommonDialog(mContext, new SimpleListener() {

                        @Override
                        public void ok() {
                            updateSwitchView(0);
                            NewActionHelp.deleteTopic(mContext, contentItem.getId(), new MyDeleteHandler());
                        }
                    }) {
                    };
                    dialog.show();
                }
            });

            //		singleInfo.im_comments.setTag(position);
            singleInfo.im_atlas.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent atlasSeeIntent = new Intent();
                    atlasSeeIntent.setClass(mContext, NewInteractionAtlasSeeActivity.class);
                    atlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, mapLists.get(position));
                    atlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_WEBURL);
                    atlasSeeIntent.putExtra(DefaultConsts.NI_POSITION, 0);
                    mContext.startActivity(atlasSeeIntent);
                }
            });
            singleInfo.gridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> v1, View v2, int pos, long arg3) {
                    Intent atlasSeeIntent = new Intent();
                    atlasSeeIntent.setClass(mContext, NewInteractionAtlasSeeActivity.class);
                    atlasSeeIntent.putExtra(DefaultConsts.NI_ATLASSEE_URL, mapLists.get(position));
                    atlasSeeIntent.putExtra(DefaultConsts.FROM_TYPE, DefaultConsts.NI_FROM_WEBURL);
                    atlasSeeIntent.putExtra(DefaultConsts.NI_POSITION, pos);

                    mContext.startActivity(atlasSeeIntent);

                }
            });
            if (Const.UserStaffId.equals(contentItem.getAuthorId() + "") || addressBookInfoDao.getByuserId(contentItem.getAuthorId()) != null)
                singleInfo.im_headportrait.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent personalInfoIntent = new Intent(mContext, ChatPersonalInfoActivity.class);
                        AddressBookInfo addressBookInfo = addressBookInfoDao.getByuserId(Const.UserStaffId.equals(contentItem.getAuthorId() + "") ? Const.UserStaffId : contentItem.getAuthorId());
                        personalInfoIntent.putExtra("contactInfo", (Serializable) addressBookInfo);
                        GroupBean groupBean = groupDao.getById(addressBookInfo.getGroupId());
                        personalInfoIntent.putExtra("groupName", groupBean.getName());//mGroupData.get(groupPosition).getName()
                        mContext.startActivity(personalInfoIntent);
                    }
                });
            return convertView;
        }
    }

    OnClickListener deleteOnclickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            final int pos = (Integer) v.getTag();
            final long topicId = mContentItemList.get(pos).getId();
            CommonDialog dialog = new CommonDialog(mContext, new SimpleListener() {

                @Override
                public void ok() {
                    updateSwitchView(0);
                    NewActionHelp.deleteTopic(mContext, topicId, new MyDeleteHandler());
                    //					                                        NewActionHelp.deleteTopic(mContext, topicId, new TextHttpResponseHandler()
                    //					                                        {
                    //
                    //						                                        @Override
                    //						                                        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
                    //							                                        updateSwitchView(-1);
                    //						                                        }
                    //
                    //						                                        @Override
                    //						                                        public void onSuccess(int arg0, Header[] arg1, String arg2) {
                    //							                                        updateSwitchView(0);
                    //							                                        getNormalData(1);
                    //						                                        }
                    //					                                        });
                    //
                }
            }) {
            };

            dialog.show();
        }
    };
    //item评论点击监听
    OnClickListener commentsOnclickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    };

    private class MyDeleteHandler
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
            updateSwitchView(-1);
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, String arg2) {
            getNormalData(1);
        }

    }

    private class SingleinfoViewHolder {
        //		FrameLayout      im_bigimage_ll;
        RelativeLayout im_bigimage_ll;
        TextView tv_publishtime, tv_info_title, tv_info_from, tv_delete;
        ImageView im_bigimage, im_atlas, im_managerlabel;
        TextView tv_comments_count;
        ImageView im_comments;
        ImageView im_headportrait;
        NoScrollGridView gridView;
    }

    /******************************
     * GridView适配器
     *****************************************/
    private class GridViewAdapter
            extends
            BaseAdapter {
        private List<String> imaList = new ArrayList<String>();
        private ImageView picView = new ImageView(mContext);
        private HolderView holder;
        private List<List<Integer>> list4;

        public GridViewAdapter(List<String> List, List<List<Integer>> list4) {
            this.imaList = List;
            this.list4 = list4;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imaList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return imaList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup arg2) {

            if (view == null)

            {

                view = View.inflate(mContext, R.layout.gridview_item, null);
                holder = new HolderView();
                holder.iv_item = (ImageView) view.findViewById(R.id.iv_gridview_item);
                //				holder.iv_item.setLayoutParams(new LayoutParams((MomentsPage.width-200)/3,(MomentsPage.width-200)/3));
                holder.iv_item.setLayoutParams(new LayoutParams((MomentsPage.width / 4 * 3 - 10) / 3, (MomentsPage.width / 4 * 3 - 10) / 3));
                //				view = picView;
                view.setTag(holder);
            } else {
                holder = (HolderView) view.getTag();
            }
            //			if (list4 != null && list4.size() > 0 && list4.size() > position && list4.get(position) != null && list4.get(position).get(1) != null)
            //			{
            //				int width = list4.get(position).get(0);
            //				int height = list4.get(position).get(1);
            //				holder.iv_item.setLayoutParams(new LayoutParams(500, 500));
            //			}
            //			Glide.with(mContext).load(imaList.get(position)).placeholder(R.drawable.moments_default_bg).into(holder.iv_item);
            GlideUtil.load(mContext,imaList.get(position),R.drawable.enterprise_default, holder.iv_item);
            return view;
        }

        private class HolderView {
            ImageView iv_item;
        }

    }

    /****************************** 一些私有的方法 *****************************************/
    //调用普通用户的接口   --  有分页信息
    //	private void getUserDatas() {
    //		NewActionHelp.qryTopicList(mContext, currentPage, PAGESIZE, new ObjectHttpResponseHandler<NewInteractionColumn>()
    //		{
    //
    //			@Override
    //			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    //			}
    //
    //			@Override
    //			public void onSuccess(int statusCode, Header[] headers, NewInteractionColumn object, String responseString) {
    //
    //				List<NewInteractionInfo> contentItems = object.getContentList();
    //				PageBean pagedto = object.getPageDto();
    //				//removeAudioAndVideo(contentItems);//临时移除音视频的数据
    //				if (contentItems == null || contentItems.size() == 0)
    //				{
    //					//取到的内空为空
    //					hasMore = false;
    //					baseActivity.getUIHandler().post(new Runnable()
    //					{
    //						@Override
    //						public void run() {
    //							if (contentViewListener != null)
    //							{
    //								contentViewListener.OnLoadDataCompleted(2);//装载更多
    //							}
    //							if (currentPage == 1)
    //							{//只有当前是重新刷新时， 才更新ui为无内容
    //								updateSwitchView(2);//内容为空
    //							}
    //						}
    //					});
    //					return;
    //				}
    //				hasMore = contentItems.size() < PAGESIZE ? false : true;
    //				if (currentPage == 1)
    //				{//刷新
    //					mContentItemList = contentItems;
    //				}
    //				else
    //				{//取下一页
    //					mContentItemList.addAll(contentItems);
    //				}
    //				//				NewInteractionColumn lastItem = mContentItemList.get(mContentItemList.size() - 1);
    //				//				currentPublishTime = lastItem.getPublishTime();
    //				currentPublishTime = contentItems.get(mContentItemList.size() - 1).getPublishTime();
    //				//刷新UI
    //				baseActivity.getUIHandler().post(new Runnable()
    //				{
    //					@Override
    //					public void run() {
    //						refreshUIData();
    //					}
    //				});
    //			}
    //
    //			@Override
    //			public Type getType() {
    //				return new TypeToken<NewInteractionColumn>()
    //				{
    //				}.getType();
    //			}
    //		});
    //	}

}
